﻿namespace Witcraft.Halcyone.ServiceModel
{
    using System.Collections.Generic;
    using System.Linq;
    using System.Text.RegularExpressions;

    internal static class StringExtensions
    {
        #region Constants and Fields

        private static readonly Regex conversionRegex = new Regex(
            "(?<ConversionCapture>{.*?})", RegexOptions.ExplicitCapture);

        private static readonly Regex redundantSlashesRegex = new Regex(@"[//\\]+");

        #endregion

        #region Public Methods

        /// <summary>
        /// Inserts parameters to uri pattern
        /// </summary>
        public static string InsertUriParameters(this string uriPattern, IDictionary<string, string> parameters)
        {
            string format = conversionRegex.Replace(
                uriPattern,
                m =>
                    {
                        string paramName = m.Value.Trim('{', '}');
                        if (parameters.ContainsKey(paramName))
                        {
                            return parameters[paramName];
                        }
                        return m.Value;
                    });

            return string.Format(format, parameters);
        }

        public static string RemoveRedundantSlashes(this string path)
        {
            string fixedPath = redundantSlashesRegex.Replace(path, @"/").Replace(@"http:/", @"http://");

            return fixedPath;
        }

        public static IEnumerable<string> GetUriPatternParameterNames(this string uriPattern)
        {
            return from Match match in conversionRegex.Matches(uriPattern) select match.Value.Trim('{', '}');
        }

        #endregion
    }
}